using POC.Common;
using Unity.Collections;
using Unity.Entities;
using Unity.NetCode;

namespace POC.Client
{
    [WorldSystemFilter(WorldSystemFilterFlags.ClientSimulation | WorldSystemFilterFlags.ThinClientSimulation)]          //只在客户端上运行
    public partial struct ClientRequestGameEntrySystem : ISystem
    {
        private EntityQuery _pendingNetworkIdQuery;

        public void OnCreate(ref SystemState state)
        {
            //筛选出必须有NetworkId且没有NetworkStreamInGame组件的Entity
            var builder = new EntityQueryBuilder(Allocator.Temp).WithAll<NetworkId>().WithNone<NetworkStreamInGame>();
            _pendingNetworkIdQuery = state.GetEntityQuery(builder);
            state.RequireForUpdate(_pendingNetworkIdQuery);
            state.RequireForUpdate<ClientTeamRequest>();
        }

        public void OnUpdate(ref SystemState state)
        {
            var requestedTeam = SystemAPI.GetSingleton<ClientTeamRequest>().Value;
            var entityCommandBuffer = new EntityCommandBuffer(Allocator.Temp);
            var pendingNetworkIds = _pendingNetworkIdQuery.ToEntityArray(Allocator.Temp);
            //添加NetworkStreamInGame组件
            foreach (var pendingNetworkId in pendingNetworkIds)
            {
                entityCommandBuffer.AddComponent<NetworkStreamInGame>(pendingNetworkId);
                var requestTeamEntity = entityCommandBuffer.CreateEntity();
                //携带上客户端希望加入的队伍
                entityCommandBuffer.AddComponent(requestTeamEntity, new MobaTeamRequest
                {
                    Value = requestedTeam
                });
                entityCommandBuffer.AddComponent(requestTeamEntity, new SendRpcCommandRequest
                {
                    TargetConnection = pendingNetworkId
                });
            }
            entityCommandBuffer.Playback(state.EntityManager);
        }
    }
}